package cn.marc.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONObject;

import com.baidu.aip.face.AipFace;

import cn.marc.jdbc.EdenDataBase;

public class EdenServlet extends HttpServlet {
	private static final long serialVersionUID = -6700774425590999372L;
	public static final String APP_ID = "9804270";
	public static final String API_KEY = "0r9rSna8yu5aKexLPHop0NTl";
	public static final String SECRET_KEY = "x1YoO0MTQ5I8iBcXQ1UECn5Ilz5SXDj1";
	private static String similar = "无法识别";

	@Override
	protected void service(HttpServletRequest httpServletRequest, 
			HttpServletResponse httpServletResponse) throws ServletException, IOException {
		switch (httpServletRequest.getParameter("func")) {
		case "login":
			if (login(httpServletRequest.getParameter("account"), 
					httpServletRequest.getParameter("password"))) {
				PrintWriter printWriter = httpServletResponse.getWriter();
				printWriter.print("Login--Success");
				printWriter.flush();
				printWriter.close();
			} else {
				PrintWriter printWriter = httpServletResponse.getWriter();
				printWriter.print("Login--Failed");
				printWriter.flush();
				printWriter.close();
			}
			break;
			
		case "register":
			if (register(httpServletRequest.getParameter("account"), 
					httpServletRequest.getParameter("password"), 
					httpServletRequest.getParameter("nickname"))) {
				PrintWriter printWriter = httpServletResponse.getWriter();
				printWriter.print("Register--Success");
				printWriter.flush();
				printWriter.close();
			} else {
				PrintWriter printWriter = httpServletResponse.getWriter();
				printWriter.print("Register--Failed");
				printWriter.flush();
				printWriter.close();
			}
			break;
			
		case "recognize":
			faceRecognize(httpServletRequest.getParameter("image"));
			
			httpServletResponse.setCharacterEncoding("UTF-8");
			PrintWriter printWriter;
			try {
				printWriter = httpServletResponse.getWriter();
				printWriter.print("The people is "+similar);
				printWriter.flush();
				printWriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;

		default:
			break;
			
		}
	}
	
	private void faceRecognize(String image) {
		String imagePath1 = this.getServletConfig().getServletContext().getRealPath("/pictures/hlh.jpg");
        String imagePath2 = this.getServletConfig().getServletContext().getRealPath("/pictures/mf.jpg");
        String imagePath3 = this.getServletConfig().getServletContext().getRealPath("/pictures/sjy.jpg");
        String imagePath4 = this.getServletConfig().getServletContext().getRealPath("/pictures/ybr.jpg");
        byte[] bytes1 = null;
        byte[] bytes2 = null;
        byte[] bytes3 = null;
        byte[] bytes4 = null;
        try {
			FileInputStream fis1 = new FileInputStream(new File(imagePath1));
			FileInputStream fis2 = new FileInputStream(new File(imagePath2));
			FileInputStream fis3 = new FileInputStream(new File(imagePath3));
			FileInputStream fis4 = new FileInputStream(new File(imagePath4));
			bytes1 = new byte[fis1.available()];
			bytes2 = new byte[fis2.available()];
			bytes3 = new byte[fis3.available()];
			bytes4 = new byte[fis4.available()];
			fis1.read(bytes1);
			fis2.read(bytes2);
			fis3.read(bytes3);
			fis4.read(bytes4);
			fis1.close();
			fis2.close();
			fis3.close();
			fis4.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[][] bytes = new byte[5][];;
		byte[] bytes0 = Base64.decodeBase64(image);
		bytes[0] = bytes0;
		bytes[1] = bytes1;
		bytes[2] = bytes2;
		bytes[3] = bytes3;
		bytes[4] = bytes4;
		System.out.println("hlh: "+bytes1.toString());
		System.out.println("mf: "+bytes2.toString());
		System.out.println("sjy: "+bytes3.toString());
		System.out.println("ybr: "+bytes4.toString());
		System.out.println("someone: "+bytes0.toString());
		AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
		client.setConnectionTimeoutInMillis(2000);
		client.setSocketTimeoutInMillis(60000);
		System.out.println("------please wait------");
		new Thread(new Runnable() {
			@Override
			public void run() {
				JSONObject response = client.match(bytes, new HashMap<String, String>());
				System.out.println(response.toString());
				JSONArray jsonArray = response.getJSONArray("result");
				double a = jsonArray.getJSONObject(0).getDouble("score");
				double b = jsonArray.getJSONObject(1).getDouble("score");
				double c = jsonArray.getJSONObject(2).getDouble("score");
				double d = jsonArray.getJSONObject(3).getDouble("score");
//				String similar = "无法识别";
				if (a>b) {
					if (a>c) {
						if (a>d) {
							if (a>80) {
								similar = "黄璐晗";
							}
						} else {
							if (d>80) {
								similar = "杨博然";
							}
						}
					} else {
						if (c>d) {
							if (c>80) {
								similar = "史佳瑶";
							}
						} else {
							if (d>80) {
								similar = "杨博然";
							}
						}
					}
				} else {
					if (b>c) {
						if (b>d) {
							if (b>80) {
								similar = "莫非";
							}
						} else {
							if (d>80) {
								similar = "杨博然";
							}
						}
					} else {
						if (c>d) {
							if (c>80) {
								similar = "史佳瑶";
							}
						} else {
							if (d>80) {
								similar = "杨博然";
							}
						}
					}
				}
				System.out.println(similar);
			}
			
		}).start();
		
	}
	
	private boolean login(String account, String password) {
		EdenDataBase edenDataBase = new EdenDataBase();
		
//		edenDataBase.setSql("SELECT user_table_password FROM eden_schema.user_table WHERE account_user_table = '"+account+"'");
		
		edenDataBase.setSelect(true);
		edenDataBase.execute();
		if (!edenDataBase.pw.equals(password)) {
			System.out.println("pw wrong!");
			return false;
		}
		
		edenDataBase.update(account, "user_table_status", "online");
		return edenDataBase.execute();
		
	}
	
	private boolean register(String account, String password, String nickname) {
		EdenDataBase edenDataBase = new EdenDataBase();
		edenDataBase.insert(account, password, nickname);
		return edenDataBase.execute();
	}

}
